<template>
  <a-modal
    :title="formType === 1 ? '新增模板' : '编辑模板'"
    :width="1280"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :keyboard="false"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-form :form="form">
      <a-form-item label="模板名称" :label-col="labelCol" :wrapper-col="wrapperCol" v-bind="validator.nameValidProps">
        <s-input
          :limit="64"
          v-decorator="[
            'name',
            {
              rules: [
                {
                  required: true,
                  message: $t('common.emptyErr', { name: $t('common.name').toLowerCase() }),
                  whitespace: true
                },
                { validator: validator.nameValidator }
              ]
            }
          ]"
        />
      </a-form-item>
      <a-form-item>
        <a-table a-table rowKey="id" :columns="columns" :dataSource="tableData" :pagination="false">
          <template slot="mon" slot-scope="text">
            <a-select
              style="width: 135px;"
              size="small"
              :value="text.shiftsId"
              @select="
                val => {
                  onShiftSelect(val, 'mon');
                }
              "
            >
              <a-select-option v-for="item in shifts" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
            </a-select>
          </template>
          <template slot="tue" slot-scope="text">
            <a-select
              style="width: 135px;"
              size="small"
              :value="text.shiftsId"
              @select="
                val => {
                  onShiftSelect(val, 'tue');
                }
              "
            >
              <a-select-option v-for="item in shifts" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
            </a-select>
          </template>
          <template slot="wed" slot-scope="text">
            <a-select
              style="width: 135px;"
              size="small"
              :value="text.shiftsId"
              @select="
                val => {
                  onShiftSelect(val, 'wed');
                }
              "
            >
              <a-select-option v-for="item in shifts" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
            </a-select>
          </template>
          <template slot="thu" slot-scope="text">
            <a-select
              style="width: 135px;"
              size="small"
              :value="text.shiftsId"
              @select="
                val => {
                  onShiftSelect(val, 'thu');
                }
              "
            >
              <a-select-option v-for="item in shifts" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
            </a-select>
          </template>
          <template slot="fri" slot-scope="text">
            <a-select
              style="width: 135px;"
              size="small"
              :value="text.shiftsId"
              @select="
                val => {
                  onShiftSelect(val, 'fri');
                }
              "
            >
              <a-select-option v-for="item in shifts" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
            </a-select>
          </template>
          <template slot="sat" slot-scope="text">
            <a-select
              style="width: 135px;"
              size="small"
              :value="text.shiftsId"
              @select="
                val => {
                  onShiftSelect(val, 'sat');
                }
              "
            >
              <a-select-option v-for="item in shifts" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
            </a-select>
          </template>
          <template slot="sun" slot-scope="text">
            <a-select
              style="width: 135px;"
              size="small"
              :value="text.shiftsId"
              @select="
                val => {
                  onShiftSelect(val, 'sun');
                }
              "
            >
              <a-select-option v-for="item in shifts" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
            </a-select>
          </template>
        </a-table>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import cloneDeep from 'lodash.clonedeep';
import { asyncValidateMixin } from '@/utils/mixin';
import { getShifts } from '@/api/shift';
import { createUserShiftConfig, updateUserShiftConfig, validateUserShiftConfigPropertyField } from '@/api/shift';
import { SInput } from '@/components';
export default {
  name: 'ShiftTempForm',
  mixins: [asyncValidateMixin],
  components: {
    SInput
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 2 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      shifts: [],
      visible: false,
      loading: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      formType: 1, // 1-新增 2-编辑
      tableData: [],
      id: 0
    };
  },
  computed: {
    columns() {
      return [
        {
          title: '周一',
          dataIndex: 'mon',
          scopedSlots: { customRender: 'mon' }
        },
        {
          title: '周二',
          dataIndex: 'tue',
          scopedSlots: { customRender: 'tue' }
        },
        {
          title: '周三',
          dataIndex: 'wed',
          scopedSlots: { customRender: 'wed' }
        },
        {
          title: '周四',
          dataIndex: 'thu',
          scopedSlots: { customRender: 'thu' }
        },
        {
          title: '周五',
          dataIndex: 'fri',
          scopedSlots: { customRender: 'fri' }
        },
        {
          title: '周六',
          dataIndex: 'sat',
          scopedSlots: { customRender: 'sat' }
        },
        {
          title: '周日',
          dataIndex: 'sun',
          scopedSlots: { customRender: 'sun' }
        }
      ];
    }
  },
  watch: {
    id(val) {
      this.initAsyncValidateMixin(val);
    }
  },
  created() {
    this.initAsyncValidateMixin(this.id);
  },
  mounted() {
    const { id } = this.$store.state.user.info;
    getShifts({ userId: id }).then(res => {
      this.shifts = res.data;
      if (res.data.length === 0) {
        this.$notification.error({
          message: this.$t('common.error'),
          description: '无法获取班次信息，请联系管理员'
        });
      }
    });
  },
  methods: {
    initAsyncValidateMixin(id) {
      const validateFields = [
        {
          fieldName: 'name',
          caller: validateUserShiftConfigPropertyField,
          extraParams: {
            id
          }
        }
      ];
      this.$_asyncValidateMixin_init(validateFields);
    },

    add() {
      this.formType = 1;
      this.id = 0;
      this.visible = true;
      this.$nextTick(() => {
        this.resetForm();
      });
    },

    edit(record) {
      const { id, name, data } = record;
      this.tableData = cloneDeep(data);
      this.id = id;
      this.formType = 2;
      this.visible = true;
      this.$nextTick(() => {
        this.form.setFieldsValue({ name });
      });
    },

    onShiftSelect(val, date) {
      this.$set(this.tableData, 0, { ...this.tableData[0], [date]: { shiftsId: val } });
    },

    convertData() {
      let data = [];
      for (let prop in this.tableData[0]) {
        const item = this.tableData[0];
        if (item.hasOwnProperty(prop)) {
          if (prop !== 'id') {
            data.push({
              id: item[prop].id || 0,
              shiftsId: item[prop].shiftsId,
              date: prop
            });
          }
        }
      }
      return data;
    },

    handleSubmit() {
      const {
        form: { validateFields, getFieldsValue }
      } = this;

      validateFields((errors, values) => {
        if (!errors) {
          const { name } = getFieldsValue();
          const data = this.convertData();
          const model = {
            id: this.id,
            name,
            data
          };
          this.confirmLoading = true;
          if (this.formType === 1) {
            createUserShiftConfig(model)
              .then(res => {
                this.visible = false;
                this.$message.success(res.message, 1);
                this.resetForm();
                this.$emit('ok', Object.assign({}, model, { formType: this.formType }));
              })
              .finally(() => {
                this.confirmLoading = false;
              });
          } else if (this.formType === 2) {
            updateUserShiftConfig(model)
              .then(res => {
                this.visible = false;
                this.$message.success(res.message, 1);
                this.resetForm();
                this.$emit('ok', Object.assign({}, model, { formType: this.formType }));
              })
              .finally(() => {
                this.confirmLoading = false;
              });
          }
        }
      });
    },

    handleCancel() {
      this.resetForm();
      this.visible = false;
    },

    resetForm() {
      this.form.setFieldsValue({ name: '' });
      this.tableData = [
        {
          id: 0,
          mon: {
            shiftsId: ''
          },
          tue: {
            shiftsId: ''
          },
          wed: {
            shiftsId: ''
          },
          thu: {
            shiftsId: ''
          },
          fri: {
            shiftsId: ''
          },
          sat: {
            shiftsId: ''
          },
          sun: {
            shiftsId: ''
          }
        }
      ];
    }
  }
};
</script>
